package com.sunpy.niohttp.file;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    /**
     * 根据包名查找包下所有的类名
     * @param packagePath 包名
     * @return 类名集合
     */
    public static List<String> findClassByPackagePath(@NotNull String packagePath) {
        String filePackagePath = packagePath.replace('.', '/');
        URL url = ClassLoader.getSystemResource(filePackagePath);

        if (url == null) {
            System.out.println("传入的路径错误，无法找到对应的文件！");
            return null;
        }

        if (url.getProtocol().equalsIgnoreCase("file")) {
            File file = new File(url.getFile());
            if (file.exists() && file.isDirectory()) {
                String[] arr = file.list();
                List<String> clazzNameList = new ArrayList<>();

                if (arr == null) {
                    System.out.println("该路径下不存在java类");
                    return clazzNameList;
                }

                for (String className : arr) {
                    int namePosition = className.indexOf(".class");
                    String clazzName = className.substring(0, namePosition);
                    clazzNameList.add(clazzName);
                }

                return clazzNameList;
            }
        }

        return null;
    }
}
